package gqz.testdemo.BtBleDemo;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.text.SimpleDateFormat;
import java.util.Locale;

import gqz.testdemo.R;

import static gqz.testdemo.BtBleDemo.BleClientDemo.REQUEST_BT_ENABLE_CODE;

/**
 * Created by Administrator on 2018/9/19.
 */

public class BTServer extends Activity implements View.OnClickListener {
    String TAG = "BTServer-->";

    public static final String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    BluetoothAdapter ba;

    private RecyclerView mRecyclerView;
    private RvAdapter mRvAdapter;
    private RecyclerView mMessageView;
    private static MsgAdapter mMessageAdapter;
    private EditText inputEt;

    private SimpleDateFormat mDateFormat;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mMessageAdapter.addMessage(mDateFormat.format(System.currentTimeMillis()) + "  " + msg.getData().getString("msg"));
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bt);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
        }
        mDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        initView();
        registReceiver();
    }

    private void initView() {
        findViewById(R.id.bt_open).setOnClickListener(this);
        findViewById(R.id.bt_close).setOnClickListener(this);
        findViewById(R.id.bt_start).setOnClickListener(this);
        findViewById(R.id.bt_stop).setOnClickListener(this);
        findViewById(R.id.bt_send).setOnClickListener(this);
        inputEt = findViewById(R.id.bt_et);

        mRecyclerView = (RecyclerView) findViewById(R.id.devices);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRvAdapter = new RvAdapter(this);
        mRecyclerView.setAdapter(mRvAdapter);
        mRvAdapter.setOnItemClickListener(new RvAdapter.OnItemClickListener() {
            @Override
            public void onClick(BluetoothDevice device) {
            }
        });

        mMessageView = (RecyclerView) findViewById(R.id.msglist);
        mMessageView.setLayoutManager(new LinearLayoutManager(this));
        mMessageAdapter = new MsgAdapter(this);
        mMessageView.setAdapter(mMessageAdapter);
    }

    private void registReceiver() {
        IntentFilter i = new IntentFilter();
        i.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        i.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        i.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        i.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        i.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        i.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(receiver, i);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(devReceiver, filter);
    }

    private void openBT() {
        if (ba == null) {
            /**这里和传统的蓝牙有什么区别呢？*/
//            final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
//            mBluetoothAdapter = bluetoothManager.getAdapter();//ble蓝牙
            ba = BluetoothAdapter.getDefaultAdapter();//传统蓝牙
        }
        //1.设备不支持蓝牙，结束应用
        if (ba == null) {
            finish();
            return;
        }
        //2.判断蓝牙是否打开
        if (!ba.isEnabled()) {
            //没打开请求打开
            Intent btEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(btEnable, REQUEST_BT_ENABLE_CODE);
            outputLog("正在打开蓝牙");
        }
    }

    private void outputLog(String msg) {
        if (mMessageAdapter != null) {
            Message message = new Message();
            message.what = 0;
            Bundle bundle = new Bundle();
            bundle.putString("msg", msg);
            message.setData(bundle);
            handler.sendMessage(message);
            Log.d(TAG, "outputLog: " + msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_open:
                break;
            case R.id.bt_close:
                break;
            case R.id.bt_start:
                break;
            case R.id.bt_stop:
                break;
            case R.id.bt_send:
                break;
        }
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            outputLog("蓝牙正在打开...");
//                            bleEnable = false;
                            break;
                        case BluetoothAdapter.STATE_ON:
                            outputLog("蓝牙已打开");
//                            bleEnable = true;
//                            getBleOpenStatus();
//                            switch_ble.setEnabled(true);
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            outputLog("蓝牙正在关闭...");
//                            bleEnable = false;
//                            getBleOpenStatus();
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            outputLog("蓝牙已关闭");
//                            bleEnable = false;
//                            switch_ble.setEnabled(true);
                            break;
                    }
                    break;
                case BluetoothAdapter.ACTION_SCAN_MODE_CHANGED:
                    Log.i(TAG, "onReceive: scan mode changed");
//                    getAllowSearchStatus();
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    Log.i(TAG, "onReceive: discovery started");
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    Log.i(TAG, "onReceive: discovery finished");
                    break;
                case BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED:
                    Log.i(TAG, "onReceive: connection state changed");
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    switch (device.getBondState()) {
                        case BluetoothDevice.BOND_NONE:
                            Log.e(getPackageName(), "取消配对");
                            break;
                        case BluetoothDevice.BOND_BONDING:
                            Log.e(getPackageName(), "配对中");
                            break;
                        case BluetoothDevice.BOND_BONDED:
                            Log.e(getPackageName(), "配对成功");
                            break;
                    }
                    break;
            }
        }
    };

    //搜索附近蓝牙设备结果广播
    BroadcastReceiver devReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  //这个就是所获得的蓝牙设备。
                Log.i(TAG, "onReceive: name:" + device.getName() + " address:" + device.getAddress());
//                addDevByFilter(device);
//                devAdapter.notifyDataSetChanged();
                mRvAdapter.addDevice(device);
                //name:hello address:54:C9:DF:59:59:8C
                //name:JDN-W09 address:88:44:77:54:3C:F4
            }
        }
    };
}
